<script>
import {
  Scene,
  PerspectiveCamera,
  WebGLRenderer,
  Vector2,
  MeshBasicMaterial,
  Mesh,
  DirectionalLight,
  PlaneGeometry,
  TextureLoader
} from 'three'

import Detector from 'three/examples/js/Detector'

import TextureImg from 'static/grass.png'
export default {
  template: '<div style="width: 100%; height: 100%"></div>',
  data() {
    return {
      scene: null,
      camera: null,
      renderer: null,
      cube: null,
      ele: null,
      width: 0,
      height:0
    }
  },
  mounted() {
    this.ele = this.$el

    if (Detector.webgl) {
      this.threeStart()
      this.animate()
    } else {
      const warning = Detector.getWebGLErrorMessage()
      this.ele.appendChild(warning)
    }
  },
  methods: {
    initThree () {
      this.width = this.ele.clientWidth
      this.height = this.ele.clientHeight
      this.renderer = new WebGLRenderer({
        antialias: true
      })
      this.renderer.setSize(this.width, this.height)
      this.ele.appendChild(this.renderer.domElement)
      this.renderer.setClearColor(0xffffff, 1)
    },
    initCamera () {
      this.camera = new PerspectiveCamera(70, this.width / this.height, 1, 1000)
      this.camera.position.z = 400
    },
    initScene () {
      this.scene = new Scene()
    },
    initLight () {
      const light = new DirectionalLight(0xff0000, 1)
      light.position.set(10, 0, 5)
      this.scene.add(light)
    },
    initObject () {
      const geometry = new PlaneGeometry(500, 300, 1, 1)
      geometry.vertices[0].uv = new Vector2(0, 0)
      geometry.vertices[1].uv = new Vector2(1, 0)
      geometry.vertices[2].uv = new Vector2(1, 1)
      geometry.vertices[3].uv = new Vector2(0, 1)

      const texture = new TextureLoader().load(TextureImg)
      const material = new MeshBasicMaterial({ map: texture })
      const mesh = new Mesh(geometry, material)
      this.scene.add(mesh)

      window.addEventListener( 'resize', this.onWindowResize, false )
    },
    threeStart () {
      this.initThree()
      this.initCamera()
      this.initScene()
      this.initLight()
      this.initObject()
      this.renderer.clear()
      this.renderer.render(this.scene, this.camera)
    },
    onWindowResize () {
      this.camera.aspect = this.width / this.height
      this.camera.updateProjectionMatrix()
      this.renderer.setSize( this.width, this.height )
    },
    animate () {
      requestAnimationFrame( this.animate );
      this.renderer.render( this.scene, this.camera )
    }
  }
}
</script>